package com.cy.ragbase.rag;

import com.cy.ragbase.dto.CodeRagRequest;
import com.cy.ragbase.dto.CodeRagResponse;
import com.cy.ragbase.dto.CodeSearchRequest;
import com.cy.ragbase.dto.CodeSearchResponse;
import com.cy.ragbase.service.CodeBlockService;
import dev.langchain4j.agent.tool.P;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CodeRagMcpService {

    private static final Logger log = LoggerFactory.getLogger(CodeRagMcpService.class);

    @Autowired
    private CodeBlockService codeBlockService;

    /**
     * 代码库搜索工具 - 根据关键词搜索项目中的代码片段
     */
    @Tool(description = "根据关键词、标签或描述搜索代码库中的相关代码片段。" +
            "返回匹配的代码内容，供AI模型参考使用。")
    public String searchCodebase(
            @P("搜索关键词或描述") String query) {

        try {
            CodeSearchRequest searchRequest = new CodeSearchRequest();
            searchRequest.setQuery(query);
            searchRequest.setTopK(10);
            searchRequest.setThreshold(0.3f);

            log.info("代码库搜索: query='{}'", query);

            CodeSearchResponse searchResponse = codeBlockService.searchCodeBlocks(searchRequest);

            return formatCodeSearchResult(searchResponse);

        } catch (Exception e) {
            log.error("代码库搜索失败: query='{}'", query, e);
            return "搜索失败: " + e.getMessage();
        }
    }

    // === 私有辅助方法 ===

    private String formatCodeSearchResult(CodeSearchResponse searchResponse) {
        if (searchResponse.getResults() == null || searchResponse.getResults().isEmpty()) {
            return "未找到相关代码片段";
        }

        StringBuilder result = new StringBuilder();
        
        for (int i = 0; i < searchResponse.getResults().size(); i++) {
            var codeResult = searchResponse.getResults().get(i);
            
            result.append("```").append(codeResult.getLanguage() != null ? codeResult.getLanguage() : "").append("\n");
            result.append("// ").append(codeResult.getName() != null ? codeResult.getName() : "代码片段");
            
            if (codeResult.getFilePath() != null) {
                result.append(" | 文件: ").append(codeResult.getFilePath());
            }
            
            result.append(" | 相似度: ").append(String.format("%.1f%%", codeResult.getScore() * 100)).append("\n");
            
            if (codeResult.getCode() != null && !codeResult.getCode().trim().isEmpty()) {
                result.append(codeResult.getCode().trim());
            } else {
                result.append("// 代码内容为空");
            }
            
            result.append("\n```\n");
            
            if (i < searchResponse.getResults().size() - 1) {
                result.append("\n");
            }
        }

        return result.toString();
    }
}